const Book = require('../models/Book')
const db = require('../db')
const _ = require('lodash')



async function insertContents(book) {
  const contents = book.getContents()
  
  if(contents && contents.length > 0) {
    for(let i=0; i<contents.length; i++){
      // console.log('contents');
      const content = contents[i]
      const _content = _.pick(content, [
        'fileName',
        'id',
        'href',
        'text',
        'order',
        'level',
        'label',
        'pid',
        'navId',
        
      ])
      // console.log(_content);
      await db.insert(_content,'contents')
    }
  }
}

function exitsts(book) {
  const {title, author, publisher} = book
  const sql = `select * from book where title='${title}' and author='${author}' and publisher='${publisher}'`
  return db.queryOne(sql)
}

async function removeBook(book){
  if(book){
    book.reset()
  }
  if(book.fileName){
    console.log("remove......");
    const removeBookSql = `delete from book where fileName='${book.fileName}'`
    const removeContentsSql = `delete from contents where fileName='${book.fileName}'`
    await db.querySql(removeBookSql)
    await db.querySql(removeContentsSql)
  }
}

//还有很逻辑.....
function insertBook(book) {
  return new Promise(async (resolve,reject)=>{
    const result = await exitsts(book)
    if (result) {
      console.log('object');
      await removeBook(book)
      reject(new Error('电子书已存在'))
    } else {
      console.log('object insertbook.....');
      await insertContents(book)
      await db.insert(book.toDb(),"book")
      resolve()
    }
  })
}

function getBook(fileName){
  return new Promise(async (resolve, reject) => {
    const bookSql = `select * from book where fileName='${fileName}'`
    const contentsSql = `select * from contents where fileName='${fileName}' order by \`order\``
    const book = await db.queryOne(bookSql)
    const contents = await db.querySql(contentsSql)
    if (book) {
      console.log(Book.genCoverUrl(book));
      book.cover = Book.genCoverUrl(book)
      book.contentsTree = Book.genContentsTree(contents)
      resolve(book)
    }
    reject("电子书不存在")
  })
}

function updateBook(book){
  return new Promise(async (resolve,reject) => {
    try {
      if(book instanceof Book) {
        const result = await getBook(book.fileName)
        if (result) {
          const model = book.toDb()
          if(+result.updateType === 0){
            reject(new Error('内置图书不能编辑'))
          } else {
            await db.update(model, 'book' ,`where fileName='${book.fileName}'`)
            resolve()
          }
        }   
      } else {
        reject(new Error('添加的图书对象不合法'))
      }
    } catch(e) {
      reject(e)
    }
  })
}

async function getCategory(){
  const sql = 'select * from category order by category asc'
  const result = await db.querySql(sql)
  const categoryList = []
  result.forEach(item => {
    categoryList.push({
      label: item.categoryText,
      value: item.category,
      num: item.num
    })
  })
  return categoryList
}

async function listBook(query){
  const {
    category ,
    author, 
    title,
    page = 1,
    pageSize = 20,
    sort
  } = query
  const offset = (page - 1) * pageSize
  console.log(query);
  console.log(".........");
  
  let bookSql = 'select * from book'
  let where = 'where'
  author && (where = db.andLike(where, 'author', author))
  title && (where = db.andLike(where, 'title', title))
  category && (where = db.and(where, 'categoryText', category))
  if (where !== 'where') {
    bookSql = `${bookSql} ${where}`
  }
  if(sort) {
    const symbol = sort[0]
    const column = sort.slice(1)
    const order = symbol === '+' ? 'asc' : 'desc'
    bookSql = `${bookSql} order by \`${column}\`  ${order}`
  }
  let countSql = 'select count(*) as count from book'
  if (where !== 'where') {
    countSql = `${countSql} ${where}`
  }
  const count = await db.querySql(countSql)
  bookSql = `${bookSql} limit ${pageSize} offset ${offset}`
  const list = await db.querySql(bookSql)
  for(let book of list){
    book.cover = Book.genCoverUrl(book)
  }
  return { list , count:count[0].count, page, pageSize}
}

async function deleteBook(fileName){
  let book = await getBook(fileName) 
  if (book) {
    if(+book.updateType === 0) {
      throw Error('内置图书不能删除')
    } else {
      const bokObj = new Book(null,book)
      await removeBook(bokObj)
    }
  } else {
    throw Error('电子书不存在')
  }
}

module.exports = {
  insertContents,
  insertBook,
  getBook,
  updateBook,
  getCategory,
  listBook,
  deleteBook
}